/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import { connect } from "dva";
import { Form, Input, Button, Select, Row, Col } from "antd";
import StandardTable from "@/components/StandardTable";
import { debounce } from "lodash";

const { Option } = Select;

@connect(({ loading, dispat }) => ({
  dispat,
  loading: loading.effects["dispat/getSubordinatePostStations"],
}))
@Form.create()
class ServiceTable extends PureComponent {
  handleOpen = debounce(
    ({ cm_id, status }) => {
      const { page } = this.state;
      const { dispatch } = this.props;
      dispatch({
        type: "dispat/postStationsOnOff",
        payload: {
          cm_id,
          status: status == 1 ? 0 : 1,
        },
      }).then(() => {
        this.setState({ selectedRows: [] });
        this.getList({ page });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  handleStandardTableChange = debounce(
    pagination => {
      const { current } = pagination;
      this.getList({ page: current });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  handleSearch = debounce(
    e => {
      e.preventDefault();
      this.getList({});
      // 查询后清空全选
      this.setState({
        selectedRows: [],
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  openBatch = debounce(
    status => {
      const { selectedRows } = this.state;
      const cm_id = selectedRows.map(item => item.cm_id).join(",");
      this.handleOpen({ cm_id, status });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  constructor(props) {
    super(props);
    this.column = [
      {
        title: "驿站名称",
        key: "cm_id",
        dataIndex: "company_name",
      },
      {
        title: "联系电话",
        dataIndex: "contact_phone",
      },
      {
        title: `驿站地址`,
        dataIndex: "address",
      },
      {
        title: "开通状态",
        render: (text, record) => <span>{record.status == 1 ? "已开启" : "已关闭"}</span>,
      },
      {
        title: "操作",
        dataIndex: "status",
        render: (text, record) => (
          <a onClick={() => this.handleOpen(record)}>{text == 1 ? "关闭" : "开启"}</a>
        ),
      },
    ];
    this.state = {
      keywords: "",
      status: "all",
      selectedRows: [],
    };
    this.handleOpen = this.handleOpen.bind(this);
  }

  componentDidMount() {
    this.getList({ page: 1 });
  }

  getList = ({ page = 1 }) => {
    const { dispatch } = this.props;
    this.getFormValues(res => {
      dispatch({
        type: "dispat/getSubordinatePostStations",
        payload: {
          page,
          ...res,
        },
      });
      this.setState({ page });
    });
  };

  getFormValues = then => {
    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        pageSize: 20,
      };

      this.setState({
        status: fieldsValue.status,
        keywords: fieldsValue.keywords,
      });
      then(values);
    });
  };

  onRowSelect = selectedRows => {
    this.setState({ selectedRows });
  };

  render() {
    const {
      dispat: { postStations },
      form: { getFieldDecorator },
      loading,
    } = this.props;
    const { keywords, status, selectedRows } = this.state;
    const disabled = selectedRows.length == 0;
    return (
      <div style={{ marginTop: 24 }}>
        <Form onSubmit={this.handleSearch} layout="inline" style={{ marginBottom: "20px" }}>
          <Form.Item label="驿站名称：">
            {getFieldDecorator("keywords", {
              initialValue: keywords,
            })(
              <Input
                style={{ width: 350 }}
                type="text"
                placeholder="请输入快宝驿站的注册手机号或者驿站名称查询"
                allowClear
              />
            )}
          </Form.Item>

          <Form.Item label="开通状态">
            {getFieldDecorator("status", {
              initialValue: status,
            })(
              <Select showSearch placeholder="开启" style={{ width: "100px" }}>
                <Option key="all" value="all">
                  全部
                </Option>
                <Option key={1} value={1}>
                  开启
                </Option>
                <Option key={0} value={0}>
                  未开启
                </Option>
              </Select>
            )}
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              查询
            </Button>
          </Form.Item>
        </Form>
        <StandardTable
          rowKey="cm_id"
          loading={loading}
          data={postStations}
          columns={this.column}
          onChange={this.handleStandardTableChange}
          selectedRows={selectedRows}
          onSelectRow={this.onRowSelect}
        />
        <Row style={{ position: "absolute", bottom: "15px", width: 200 }} justify="space-between">
          <Col span={12}>
            <Button
              disabled={disabled || status == 1}
              type="primary"
              onClick={this.openBatch.bind(this, 0)}
            >
              批量开启
            </Button>
          </Col>
          <Col span={12}>
            <Button
              disabled={disabled || status == 0}
              type="primary"
              onClick={this.openBatch.bind(this, 1)}
            >
              批量关闭
            </Button>
          </Col>
        </Row>
      </div>
    );
  }
}

export default ServiceTable;
